package deibay.server.frontend.communication.clients;


import java.io.IOException;
import java.util.Date;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.logging.Level;
import deibay.DeibayLogger;
import deibay.messages.PingMsg;
import deibay.network.IClientCommunicator;
import deibay.util.IClosable;

public class ClientSessionActivity implements Runnable, IClosable{

	private Hashtable<String, IClientCommunicator> sessions = null;
	private boolean keepAlive;
	private int waitSeconds; 
	
	public ClientSessionActivity(Hashtable<String, IClientCommunicator> sessions)
	{
		this.sessions = sessions;
		keepAlive = true;
		waitSeconds = 30;
	}
	
	public synchronized void run() {	
				
		synchronized(sessions)
		{
			while (sessions.isEmpty())
			{
				//System.err.println("OLAAA activity");
				try {
					sessions.wait();
				} catch (InterruptedException e) {
					DeibayLogger.getInstance().getLog().log(Level.SEVERE, "Excepcao ao lancar o wait na thread ClientSessionActivity. \n");
				}
			}
		}		
		while(keepAlive == true)
		{
			//System.err.println("OLAAA activity");			
			synchronized(sessions)
			{
				Date now = new Date(System.currentTimeMillis());			
				LinkedList<IClientCommunicator> sessionCollect = new LinkedList<IClientCommunicator>(sessions.values());
				for(IClientCommunicator communicator: (LinkedList<IClientCommunicator>) sessionCollect.clone())
				{				
					try {
						communicator.send(new PingMsg());
					} catch (IOException e) {
						DeibayLogger.getInstance().getLog().log(Level.SEVERE, "Error while sending ping message.");
					}
				}
			}					

			try {
				Thread.sleep(waitSeconds*1000);
			} catch (InterruptedException e) {				
				e.printStackTrace();
			}
		}		
	}

	public void close() {		
		keepAlive = false;
	}

	public void restart() {
		keepAlive = true;
		new Thread(this).start();
	}

}
